import type { Dispatch } from 'redux';
import { AnyAction } from 'redux';

import {
  getListDataService,
  getDetailByIdService,
  updateDataService,
  removeDataByIdService,
  addDataService,
} from '@/services/customer';

import { ICustomer, ListRequest } from '@/services/customer.d';

import ACTIONS from './actionTypes';

import { RootState } from '../store';

import { ThunkAction } from 'redux-thunk';

// 获取客户信息列表
export const getListDataAction =
  (params: ListRequest): ThunkAction<void, RootState, unknown, AnyAction> =>
  async (dispatch) => {
    dispatch({
      type: ACTIONS.FETCHING,
      payload: { isFetching: true },
    } as const);

    const res = await getListDataService(params);
    if (res) {
      dispatch({
        type: ACTIONS.INIT_CUSTOMER,
        payload: res.data,
      } as const);
    }
  };

// 根据ID获取客户信息详情
export const getDetailByIdAction =
  (params: string): ThunkAction<void, RootState, unknown, AnyAction> =>
  async (dispatch) => {
    dispatch({
      type: ACTIONS.FETCHING,
      payload: { isFetching: true },
    } as const);

    const res = await getDetailByIdService(params);
    if (res) {
      dispatch({
        type: ACTIONS.GET_DETAIL_CUSTOMER,
        payload: res.data,
      } as const);
    }
  };

// 删除客户信息
export const removeDataByIdAction =
  (params: string): ThunkAction<void, RootState, unknown, AnyAction> =>
  async (dispatch) => {
    dispatch({
      type: ACTIONS.FETCHING,
      payload: { isFetching: true },
    } as const);
    const res = await removeDataByIdService(params);
    if (res) {
      await dispatch(getListDataAction({ pageSize: 10, page: 1 }));
      await dispatch({
        type: ACTIONS.REMOVE_CUSTOMER,
        payload: '用户删除成功',
      } as const);
    }
  };

// 修改客户信息
export const updateDataAction =
  (params: ICustomer): ThunkAction<void, RootState, unknown, AnyAction> =>
  async (dispatch) => {
    dispatch({
      type: ACTIONS.FETCHING,
      payload: { isFetching: true },
    } as const);
    const res = await updateDataService(params);
    if (res) {
      await dispatch(getListDataAction({ pageSize: 10, page: 1 }));
      dispatch({
        type: ACTIONS.UPDATE_CUSTOMER,
        payload: '用户修改成功',
      } as const);
    }
  };

// 添加客户信息

export const addDataAction =
  (params: ICustomer): ThunkAction<void, RootState, unknown, AnyAction> =>
  async (dispatch) => {
    dispatch({
      type: ACTIONS.FETCHING,
      payload: { isFetching: true },
    } as const);

    const res = await addDataService(params);
    if (res) {
      await dispatch(getListDataAction({ pageSize: 10, page: 1 }));
      dispatch({
        type: ACTIONS.ADD_CUSTOMER,
        payload: '用户添加成功',
      } as const);
    }
  };

export const updateOpMessageAction = (text: string | null) => {
  return {
    type: ACTIONS.UPDATE_OP_MESSAGE,
    payload: text,
  };
};
